package com.lcke.system.controller;

import cn.hutool.core.util.IdUtil;
import com.lcke.common.config.LemonCnt;
import com.lcke.common.login.LoginCache;
import com.lcke.common.login.User;
import com.lcke.common.rest.Result;
import com.lcke.common.util.HttpContext;
import com.lcke.system.model.SystemUser;
import com.lcke.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
@RequestMapping("/system")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录 （ 密码登录）
     *
     * @param param
     * @return
     */
    @RequestMapping("/login")
    public String loginPost(SystemUser param, HttpServletRequest request, HttpServletResponse response) {
        SystemUser user = userService.findByNameAndPassword(param);
        if (user != null) {
            String token = IdUtil.fastSimpleUUID();
            // 信息存储到session中
            LoginCache.setUser(token, user);
            Cookie cookie = new Cookie(LoginCache.TOKEN, token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return "redirect:/index";
        } else {
            request.setAttribute("error", "用户名或密码错误");
            // 这里根据实际情况进行校验
            return "login";
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public String logout() {
        LoginCache.removeUser(HttpContext.getToken());
        return "login";
    }

    /**
     * 身份切换
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/switch")
    public Result roleswitch(HttpServletRequest request, String userId) {
        // 这里要清除session中信息
        User currentUser = HttpContext.getUser();
        if (currentUser == null) {
            return Result.error("你已退出登录！");
        }
        if (userId.equals(String.valueOf(currentUser.getUserId()))) {
            return Result.error("新身份和旧身份相同！");
        }
        SystemUser systemUser = userService.switchRoleByName(currentUser);
        request.setAttribute(LemonCnt.LOGIN_USER, systemUser);
        LoginCache.setUser(HttpContext.getToken(), systemUser);
        return Result.ok("切换成功！");
    }

}
